<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-07-01 09:37:19
 * @Description: 拼多多订单自动同步
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-10-04 11:23:14
 * @FilePath: /qingshanERP/app/Console/Commands/Pdd/SyncOrder.php
 */

namespace App\Console\Commands\Pdd;

use DB;
use App\Customize\PddRequest;
use App\Models\QingShanERP\GoodSpec;
use Illuminate\Console\Command;
use App\Models\QingShanERP\Shop;
use App\Models\QingShanERP\Order;
use App\Models\QingShanERP\OrderGood;
use App\Models\QingShanERP\OrderPddData;
use Log;

class SyncOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pdd-sync-order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '拼多多订单自动同步';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {
            // Order::where('id','>',0)->update(['last_updated_at'=>'2021-07-01 00:00:00']);
            // dd(1);
            // 找所有门店
            $all_shop = Shop::where('type',4)->where('del_flag',0)->get();
            foreach ($all_shop as $s) {
                // 当前店铺最后一次拉取订单的时间
                $starttime = Order::where('shop_id',$s->id)->orderBy('last_updated_at','desc')->value('last_updated_at');
                // 如果是第一次拉取，就拉取两个月前的
                $starttime = is_null($starttime) ? date('Y-m-d H:i:s', time() - 60 * 24 * 3600) : $starttime;
                $start_time = strtotime($starttime);
                // 如果token有效
                if ($s->expires_at >= time() && !is_null($s->access_token)) {
                    while ($start_time < time()) {
                        $data = [];
                        $params['access_token'] = $s->access_token;
                        $params['timestamp'] = strval(time());
                        $params['is_lucky_flag'] = 0;
                        $params['order_status'] = 5;
                        $params['start_updated_at'] = $start_time;
                        $params['end_updated_at'] = $start_time + 30 * 60;
                        dump(date('Y-m-d H:i:s', $params['start_updated_at']) . ' - ' . date('Y-m-d H:i:s', $params['end_updated_at']));
                        $params['page_size'] = 100;
                        $params['refund_status'] = 5;
                        $params['use_has_next'] = true;
                        $params['page'] = 1;
                        // 循环拉取一天的订单
                        $has_next = true;
                        while ($has_next) {
                            $tmp = PddRequest::request('pdd.order.number.list.increment.get', $params);
                            if (!isset($tmp['order_sn_increment_get_response'])) {
                                dump($tmp['error_response']['error_msg']);
                            } else {
                                $has_next = $tmp['order_sn_increment_get_response']['has_next'];
                                if ($has_next) {
                                    $params['page'] = $params['page'] + 1;
                                }
                                if (is_array($tmp['order_sn_increment_get_response']['order_sn_list'])) {
                                    $data = array_merge($data, $tmp['order_sn_increment_get_response']['order_sn_list']);
                                }
                            }
                            sleep(1);
                        }
                        dump(count($data));
                        // 开始插入数据
                        DB::beginTransaction();
                        try {
                            foreach ($data as $d) {
                                dump('当前订单号：' . $d['order_sn']);
                                // 查有没有，有更新，没有创建
                                $hav = Order::where('type', $s->type)->where('shop_id', $s->id)->where('order_sn', $d['order_sn'])->first();
                                if (is_null($hav)) {
                                    $order_create = ['type' => $s->type, 'shop_id' => $s->id, 'order_sn' => $d['order_sn'], 'trade_type' => $d['trade_type'],'confirm_time' => $d['confirm_time'], 'last_updated_at' => $d['updated_at'], 'confirm_status' => $d['confirm_status'], 'order_status' => $d['order_status'], 'after_sales_status' => $d['after_sales_status'], 'pay_amount' => $d['pay_amount'], 'logistics_id' => $d['logistics_id'], 'tracking_number' => $d['tracking_number']];
                                    if (isset($d['remark_tag'])) {
                                        $order_create['remark_tag'] = $d['remark_tag'];
                                        $order_create['remark_tag_name'] = $d['remark_tag_name'];
                                    }
                                    if ($d['shipping_time'] != '') {
                                        $order_create['shipping_time'] = $d['shipping_time'];
                                    }
                                    if ($d['receive_time'] != '') {
                                        $order_create['receive_time'] = $d['receive_time'];
                                    }
                                    $order = Order::create($order_create);
                                    // 订单附表，拼多多表
                                    $pdd_create = [
                                        'order_id' => $order->id,
                                        'created_time' => $d['created_time'],
                                        'receiver_name' => $d['receiver_name'],
                                        'receiver_phone' => $d['receiver_phone'],
                                        'receiver_address' => $d['receiver_address'],
                                        'address' => $d['address'],
                                        'province' => $d['province'],
                                        'city' => $d['city'],
                                        'town' => $d['town'],
                                        'goods_amount' => $d['goods_amount'],
                                        'discount_amount' => $d['discount_amount'],
                                        'postage' => $d['postage'],
                                        'order_change_amount' => $d['order_change_amount'],
                                        'pay_no' => $d['pay_no'],
                                        'pay_type' => $d['pay_type'],
                                        'refund_status' => $d['refund_status'],
                                        'last_ship_time' => $d['last_ship_time'],
                                        'remark' => $d['remark'],
                                        'self_contained' => $d['self_contained'],
                                        'risk_control_status' => $d['risk_control_status'],
                                        'shipping_type' => $d['shipping_type'],
                                        'yyps_date' => $d['yyps_date'],
                                        'delivery_one_day' => $d['delivery_one_day'],
                                        'duoduo_wholesale' => $d['duoduo_wholesale'],
                                        'mkt_biz_type' => $d['mkt_biz_type'],
                                        'free_sf' => $d['free_sf'],
                                        'is_pre_sale' => $d['is_pre_sale'],
                                        'invoice_status' => $d['invoice_status'],
                                        'is_pre_sale' => $d['is_pre_sale'],
                                        'buyer_memo' => $d['buyer_memo'],
                                        'stock_out_handle_status' => $d['stock_out_handle_status'],
                                        'is_stock_out' => $d['is_stock_out'],
                                    ];
                                    if ($d['pay_time'] != '') {
                                        $pdd_create['pay_time'] = $d['pay_time'];
                                    }
                                    if ($d['yyps_time'] != '') {
                                        $pdd_create['yyps_time'] = $d['yyps_time'];
                                    }
                                    if ($d['urge_shipping_time'] != '') {
                                        $pdd_create['urge_shipping_time'] = $d['urge_shipping_time'];
                                    }
                                    OrderPddData::create($pdd_create);
                                    // 商品附表
                                    $goods_insert = [];
                                    $date = date('Y-m-d H:i:s');
                                    foreach ($d['item_list'] as $g) {
                                        $good = GoodSpec::where('sku_id', $g['sku_id'])->where('del_flag', 0)->first();
                                        if (!is_null($good)) {
                                            $goods_insert[] = [
                                                'order_id' => $order->id,
                                                'good_id' => $good->good_id,
                                                'good_spec_id' => $good->id,
                                                'goods_spec' => $g['sku_id'],
                                                'goods_name' => $g['goods_name'],
                                                'good_spec_name' => $g['goods_spec'],
                                                'goods_price' => $g['goods_price'],
                                                'goods_img' => $g['goods_img'],
                                                'goods_count' => $g['goods_count'],
                                                'gift_flag' => 0,
                                                'created_at' => $date,
                                                'updated_at' => $date,
                                            ];
                                        }
                                    }
                                    foreach ($d['gift_list'] as $gift) {
                                        $good = GoodSpec::where('sku_id', $g['sku_id'])->where('del_flag', 0)->first();
                                        if (!is_null($good)) {
                                            $goods_insert[] = [
                                                'order_id' => $order->id,
                                                'good_id' => $good->good_id,
                                                'good_spec_id' => $good->id,
                                                'goods_spec' => $gift['sku_id'],
                                                'goods_name' => $gift['goods_name'],
                                                'good_spec_name' => $gift['goods_spec'],
                                                'goods_price' => $gift['goods_price'],
                                                'goods_img' => $gift['goods_img'],
                                                'goods_count' => $gift['goods_count'],
                                                'gift_flag' => 0,
                                                'created_at' => $date,
                                                'updated_at' => $date,
                                            ];
                                        }
                                    }
                                    OrderGood::insert($goods_insert);
                                } else {
                                    $order_update = ['last_updated_at' => $d['updated_at'], 'confirm_status' => $d['confirm_status'], 'order_status' => $d['order_status'], 'after_sales_status' => $d['after_sales_status'], 'pay_amount' => $d['pay_amount'], 'logistics_id' => $d['logistics_id'], 'tracking_number' => $d['tracking_number']];
                                    if (isset($d['remark_tag'])) {
                                        $order_update['remark_tag'] = $d['remark_tag'];
                                        $order_update['remark_tag_name'] = $d['remark_tag_name'];
                                    }
                                    if ($d['shipping_time'] != '') {
                                        $order_update['shipping_time'] = $d['shipping_time'];
                                    }
                                    if ($d['receive_time'] != '') {
                                        $order_update['receive_time'] = $d['receive_time'];
                                    }
                                    Order::where('id', $hav->id)->update($order_update);
                                    // 订单附表，拼多多表
                                    $pdd_update = [
                                        'order_id' => $hav->id,
                                        'address' => $d['address'],
                                        'province' => $d['province'],
                                        'city' => $d['city'],
                                        'town' => $d['town'],
                                        'goods_amount' => $d['goods_amount'],
                                        'discount_amount' => $d['discount_amount'],
                                        'postage' => $d['postage'],
                                        'order_change_amount' => $d['order_change_amount'],
                                        'pay_no' => $d['pay_no'],
                                        'pay_type' => $d['pay_type'],
                                        'refund_status' => $d['refund_status'],
                                        'last_ship_time' => $d['last_ship_time'],
                                        'remark' => $d['remark'],
                                        'self_contained' => $d['self_contained'],
                                        'risk_control_status' => $d['risk_control_status'],
                                        'shipping_type' => $d['shipping_type'],
                                        'yyps_date' => $d['yyps_date'],
                                        'delivery_one_day' => $d['delivery_one_day'],
                                        'duoduo_wholesale' => $d['duoduo_wholesale'],
                                        'mkt_biz_type' => $d['mkt_biz_type'],
                                        'free_sf' => $d['free_sf'],
                                        'is_pre_sale' => $d['is_pre_sale'],
                                        'invoice_status' => $d['invoice_status'],
                                        'is_pre_sale' => $d['is_pre_sale'],
                                        'buyer_memo' => $d['buyer_memo'],
                                        'stock_out_handle_status' => $d['stock_out_handle_status'],
                                        'is_stock_out' => $d['is_stock_out'],
                                    ];
                                    if ($d['receiver_name'] != '') {
                                        $pdd_update['receiver_name'] = $d['receiver_name'];
                                    }
                                    if ($d['receiver_phone'] != '') {
                                        $pdd_update['receiver_phone'] = $d['receiver_phone'];
                                    }
                                    if ($d['receiver_address'] != '') {
                                        $pdd_update['receiver_address'] = $d['receiver_address'];
                                    } 
                                    if ($d['pay_time'] != '') {
                                        $pdd_update['pay_time'] = $d['pay_time'];
                                    }
                                    if ($d['yyps_time'] != '') {
                                        $pdd_update['yyps_time'] = $d['yyps_time'];
                                    }
                                    if ($d['urge_shipping_time'] != '') {
                                        $pdd_update['urge_shipping_time'] = $d['urge_shipping_time'];
                                    }
                                    OrderPddData::where('order_id', $hav->id)->update($pdd_update);
                                }
                            }
                            DB::commit();
                        } catch (\Throwable $th) {
                            DB::rollback();
                            Log::info('pdd-sync-order error2: ' . $th->getLine() . ' - ' . $th->getMessage());
                            dd($th->getLine().' - '.$th->getMessage());
                        }
                        dump('门店<' . $s->shopname . ' - ' . date('Y-m-d H:i:s', $params['start_updated_at']) . '>订单拉取完成');
                        $start_time = $start_time + 30*60;
                        Log::info('门店<' . $s->shopname . ' - ' . date('Y-m-d H:i:s', $params['start_updated_at']) . '>订单拉取完成');
                    }
                }
            }
            dd('success');
        } catch (\Throwable $th) {
            Log::info('pdd-sync-order error: '.$th->getLine() . ' - ' . $th->getMessage());
            dd($th->getLine() . ' - ' . $th->getMessage());
        }
    }
}
